<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>API测试界面</title>
    <style>
        body {
            font-family: 'Arial', sans-serif;
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }

        h1 {
            color: #333;
            text-align: center;
        }

        .group {
            background-color: white;
            border-radius: 8px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }

        .group-title {
            font-size: 1.2rem;
            font-weight: bold;
            margin-bottom: 15px;
            color: #2c3e50;
            border-bottom: 2px solid #3498db;
            padding-bottom: 5px;
        }

        .button-container {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            margin-bottom: 15px;
        }

        button {
            padding: 10px 15px;
            background-color: #3498db;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            transition: background-color 0.3s;
        }

        button:hover {
            background-color: #2980b9;
        }

        .results {
            background-color: #f8f9fa;
            padding: 15px;
            border-radius: 4px;
            height: 300px;
            overflow-y: auto;
            border: 1px solid #ddd;
            font-family: monospace;
            white-space: pre-wrap;
        }

        .clear-btn {
            background-color: #e74c3c;
            margin-top: 10px;
        }

        .clear-btn:hover {
            background-color: #c0392b;
        }

        .success {
            color: green;
        }

        .error {
            color: red;
        }

        .info {
            color: blue;
        }
    </style>
</head>

<body>
    <h1>API测试界面</h1>

    <!-- 认证测试组 -->
    <div class="group">
        <div class="group-title">认证测试</div>
        <div style="margin-bottom: 15px;">
            <input type="text" id="username-input" placeholder="用户名" value="name" style="padding: 8px; margin-right: 10px; width: 150px;">
            <input type="password" id="password-input" placeholder="密码" value="123456" style="padding: 8px; width: 150px;">

        </div>
        <div class="button-container">
            <button id="login-btn">用户登录</button>
            <button id="refresh-token-btn">刷新令牌</button>
            <button id="invalid-token-btn">无效令牌测试</button>
        </div>
    </div>

    <!-- API测试组 -->
    <div class="group">
        <div class="group-title">API测试</div>
        <div class="button-container">
            <button id="public-api-btn">访问公开API</button>
            <button id="protected-api-btn">访问受保护API</button>
            <button id="service1-api-btn">访问服务1 API</button>
            <button id="service2-api-btn">访问服务2 API</button>
        </div>
    </div>

    <!-- WebSocket测试组 -->
    <div class="group">
        <div class="group-title">WebSocket测试</div>
        <div class="button-container">
            <button id="ws-connect-btn">连接WebSocket</button>
            <button id="ws-send-btn">发送WebSocket消息</button>
            <button id="ws-disconnect-btn">断开WebSocket连接</button>
        </div>
    </div>

    <!-- 结果显示区域 -->
    <div class="group">
        <div class="group-title">测试结果</div>
        <div class="results" id="results"></div>
        <button class="clear-btn" id="clear-results-btn">清空结果</button>
    </div>

    <!-- 引入外部资源 -->
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <script src="apiClient.js"></script>

    <script>
        // 初始化API客户端
        const apiClient = new ApiClient();

        // 结果显示区域
        const resultsElement = document.getElementById('results');

        // 添加结果到显示区域
        function addResult(message, type = 'info') {
            const timestamp = new Date().toLocaleTimeString();
            const resultLine = document.createElement('div');
            resultLine.className = type;
            resultLine.textContent = `[${timestamp}] ${message}`;
            resultsElement.appendChild(resultLine);
            resultsElement.scrollTop = resultsElement.scrollHeight;
        }

        // 清空结果
        document.getElementById('clear-results-btn').addEventListener('click', () => {
            resultsElement.innerHTML = '';
            addResult('结果已清空', 'info');
        });

        // 认证测试
        document.getElementById('login-btn').addEventListener('click', async () => {
            try {
                const username = document.getElementById('username-input').value;
                const password = document.getElementById('password-input').value;
                
                if (!username || !password) {
                    addResult('请输入用户名和密码', 'error');
                    return;
                }
                
                addResult('开始登录...');
                const response = await apiClient.login(username, password);
                addResult(`登录成功！令牌: ${apiClient.token.substring(0, 20)}...`, 'success');
            } catch (error) {
                addResult(error.message, 'error');
            }
        });

        // 刷新令牌
        document.getElementById('refresh-token-btn').addEventListener('click', async () => {
            try {
                addResult('开始刷新令牌...');
                await apiClient.refreshToken();
                addResult(`令牌刷新成功！新令牌: ${apiClient.token.substring(0, 20)}...`, 'success');
            } catch (error) {
                addResult(error.message, 'error');
            }
        });

        // 无效令牌测试
        document.getElementById('invalid-token-btn').addEventListener('click', async () => {
            try {
                addResult('开始无效令牌测试...');
                // 创建一个临时的axios实例进行测试
                const tempAxios = axios.create();
                await tempAxios.get(`${apiClient.gatewayUrl}/api/protected`, {
                    headers: { 'Authorization': 'Bearer invalidtoken' }
                });
                addResult('测试失败：无效令牌未被拒绝', 'error');
            } catch (error) {
                addResult(`测试成功：${error.response?.data?.message || error.message}`, 'success');
            }
        });

        // 公开API测试
        document.getElementById('public-api-btn').addEventListener('click', async () => {
            try {
                addResult('访问公开API...');
                const response = await apiClient.getPublicData();
                addResult(`公开API响应: ${JSON.stringify(response)}`, 'success');
            } catch (error) {
                addResult(error.message, 'error');
            }
        });

        // 受保护API测试
        document.getElementById('protected-api-btn').addEventListener('click', async () => {
            try {
                addResult('访问受保护API...');
                const response = await apiClient.getProtectedData();
                addResult(`受保护API响应: ${JSON.stringify(response)}`, 'success');
            } catch (error) {
                addResult(error.message, 'error');
            }
        });

        // 服务1 API测试
        document.getElementById('service1-api-btn').addEventListener('click', async () => {
            try {
                addResult('访问服务1 API...');
                const response = await apiClient.getService1Data();
                addResult(`服务1 API响应: ${JSON.stringify(response)}`, 'success');
            } catch (error) {
                addResult(error.message, 'error');
            }
        });

        // 服务2 API测试
        document.getElementById('service2-api-btn').addEventListener('click', async () => {
            try {
                addResult('访问服务2 API...');
                const response = await apiClient.getService2Data();
                addResult(`服务2 API响应: ${JSON.stringify(response)}`, 'success');
            } catch (error) {
                addResult(error.message, 'error');
            }
        });

        // WebSocket测试
        let ws = null;

        document.getElementById('ws-connect-btn').addEventListener('click', async () => {
            if (ws && ws.readyState === WebSocket.OPEN) {
                addResult('WebSocket已连接', 'info');
                return;
            }

            try {
                addResult('开始连接WebSocket...');
                // 使用统一的/api/ws/路径
                ws = await apiClient.connectWebSocket('/ws/service1');

                ws.onmessage = (event) => {
                    addResult(`收到WebSocket消息: ${event.data}`, 'info');
                };

                ws.onclose = () => {
                    addResult('WebSocket连接已关闭', 'info');
                    ws = null;
                };

                ws.onerror = (error) => {
                    addResult(`WebSocket错误: ${error.message}`, 'error');
                };

                addResult('WebSocket连接成功', 'success');
            } catch (error) {
                addResult(error.message, 'error');
            }
        });

        document.getElementById('ws-send-btn').addEventListener('click', () => {
            if (!ws || ws.readyState !== WebSocket.OPEN) {
                addResult('请先连接WebSocket', 'error');
                return;
            }

            try {
                const message = JSON.stringify({ type: 'test', data: 'Hello WebSocket!' });
                ws.send(message);
                addResult(`已发送WebSocket消息: ${message}`, 'info');
            } catch (error) {
                addResult(`WebSocket消息发送失败: ${error.message}`, 'error');
            }
        });

        document.getElementById('ws-disconnect-btn').addEventListener('click', () => {
            if (ws) {
                ws.close();
                ws = null;
                addResult('WebSocket已断开连接', 'info');
            } else {
                addResult('WebSocket未连接', 'error');
            }
        });

        // 初始信息
        addResult('测试界面已加载完成，请点击上方按钮开始测试', 'info');
        addResult('注意：请确保网关和相关服务已启动', 'info');
    </script>
</body>
</html>